/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.cx1.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import org.apache.commons.lang.StringUtils;
import org.cx1.model.Listing;
import org.cx1.model.Photo;
import org.cx1.model.ds.MockDS;
import org.cx1.model.utils.ServiceResponse;
import org.cx1.model.User;
import org.cx1.service.api.IListingService;
import org.cx1.service.api.IUserService;

/**
 *
 * @author ECH
 */
public class MUserService implements IUserService {

    @Override
    public ServiceResponse<String> create(User user) {
        ServiceResponse<String> response = new ServiceResponse<String>();
        String id = null;        
        try {            
            boolean verified = true;
            //CX: check required fields
            if (StringUtils.isEmpty(user.getEmail())) {
                response.setMessage("Your email is required.");
                verified = false;
            }
            if (StringUtils.isEmpty(user.getFirstName())) {
                response.setMessage("Your name is required.");
                verified = false;
            }
            if (StringUtils.isEmpty(user.getLastName())) {
                response.setMessage("Your name is required.");
                verified = false;
            }
            if (StringUtils.isEmpty(user.getPassword())) {
                response.setMessage("A password is required.");
                verified = false;
            }
            //CX: check existing email
            if (emailExists(user.getEmail())) {
                response.setMessage("Email is already existing.");
                verified = false;
            }
            
            if (verified) {                
                User entry = new User();
                id = UUID.randomUUID().toString();

                entry.setId(id);
                entry.setUserTypeID(user.getUserTypeID());

                entry.setBrokerID(user.getBrokerID());
                entry.setGmailID(user.getGmailID());
                entry.setYahooID(user.getYahooID());
                entry.setFacebookID(user.getFacebookID());

                entry.setEmail(user.getEmail());
                entry.setPassword(user.getPassword());

                entry.setName(user.getName());
                entry.setFirstName(user.getFirstName());
                entry.setLastName(user.getLastName());
                
                entry.setTitle(user.getTitle());
                entry.setDescription(user.getDescription());
                entry.setNotes(user.getNotes());

                //CX: contact details
                
                entry.setEmailPrimary(user.getEmailPrimary());
                entry.setEmailSecondary(user.getEmailSecondary());
                
                entry.setMobilePrimary(user.getMobilePrimary());
                entry.setMobileSecondary(user.getMobileSecondary());
                
                entry.setLandlinePrimary(user.getLandlinePrimary());
                entry.setLandlineSecondary(user.getLandlineSecondary());     
                
                entry.setActive(true);
                entry.setDateCreated(new Date());
                entry.setDateModified(new Date());

                entry.setPrimaryPhotoID(user.getPrimaryPhotoID());
                entry.setPhotoIDs(user.getPhotoIDs());
                entry.setContactIDs(user.getContactIDs());
                entry.setCompanyIDs(user.getCompanyIDs());

                MockDS.getUsers().add(entry);
                response.setResponse(id);            
            }
            response.setSuccessful(true);            
        } 
        catch (Exception ex) {
            response.setResponse(null);
            response.setSuccessful(false);
            response.setMessage(ex.getMessage());
            response.setException(ex);
            ex.printStackTrace();            
        }
        return response; 
    }

    @Override
    public ServiceResponse<List<User>> readAll(int offset, int limit) {
        ServiceResponse<List<User>> response = new ServiceResponse<List<User>>();
        List<User> users = new ArrayList<User>();
        try {            
            List<User> records = MockDS.getUsers();
            if (records != null && records.size() > 0) {
                if (offset == 0 && limit == 0) {
                    users.addAll(records);
                }
                else if (offset < records.size() && limit < records.size()) {
                    users.addAll( records.subList(offset, limit) );
                }              
            }            
            response.setResponse(users);
            response.setSuccessful(true);            
        } 
        catch (Exception ex) {
            response.setResponse(null);
            response.setSuccessful(false);
            response.setMessage(ex.getMessage());
            response.setException(ex);
            ex.printStackTrace();            
        }
        return response; 
    }

    @Override
    public ServiceResponse<User> read(String id) {
        ServiceResponse<User> response = new ServiceResponse<User>();
        User user = null;
        try {            
            List<User> records = MockDS.getUsers();   
            if (records != null && records.size() > 0) {
                for (User record : records) {
                    if (StringUtils.equalsIgnoreCase(record.getId(), id)) {
                        user = record;
                        break;
                    }
                }
            }            
            response.setResponse(user);
            response.setSuccessful(true);            
        } 
        catch (Exception ex) {
            response.setResponse(null);
            response.setSuccessful(false);
            response.setMessage(ex.getMessage());
            response.setException(ex);
            ex.printStackTrace();            
        }
        return response; 
    }

    @Override
    public ServiceResponse<Boolean> update(User user) {
        ServiceResponse<Boolean> response = new ServiceResponse<Boolean>();
        boolean success = false;
        try {            
            User targetUser = null;
            String targetID = user.getId();
            
            List<User> records = MockDS.getUsers();   
            
            if ( !StringUtils.isEmpty(targetID) && records != null && records.size() > 0) {                
                //CX: find record
                for (User record : records) {
                    if (StringUtils.equalsIgnoreCase(record.getId(), targetID)) {
                        targetUser = record;
                        break;
                    }
                }                
                //CX: update dabase record
                if (targetUser != null) {
                    targetUser.setUserTypeID(user.getUserTypeID());
                    
                    targetUser.setBrokerID(user.getBrokerID());
                    targetUser.setGmailID(user.getGmailID());
                    targetUser.setYahooID(user.getYahooID());
                    targetUser.setFacebookID(user.getFacebookID());
                    
                    targetUser.setEmail(user.getEmail());
                    targetUser.setPassword(user.getPassword());
                    
                    targetUser.setName( user.getName() );
                    
                    targetUser.setTitle(user.getTitle());
                    targetUser.setDescription(user.getDescription());
                    targetUser.setNotes(user.getNotes());
                    
                    //CX: contact details

                    targetUser.setEmailPrimary(user.getEmailPrimary());
                    targetUser.setEmailSecondary(user.getEmailSecondary());

                    targetUser.setMobilePrimary(user.getMobilePrimary());
                    targetUser.setMobileSecondary(user.getMobileSecondary());

                    targetUser.setLandlinePrimary(user.getLandlinePrimary());
                    targetUser.setLandlineSecondary(user.getLandlineSecondary());
                
                    targetUser.setPrimaryPhotoID(user.getPrimaryPhotoID());
                    targetUser.setPhotoIDs(user.getPhotoIDs());
                    targetUser.setContactIDs(user.getContactIDs());
                    targetUser.setCompanyIDs(user.getCompanyIDs());
                    
                    targetUser.setDateModified(new Date());            
                    success = true;
                }
                
            }            
            response.setResponse(success);
            response.setSuccessful(true);            
        } 
        catch (Exception ex) {
            response.setResponse(null);
            response.setSuccessful(false);
            response.setMessage(ex.getMessage());
            response.setException(ex);
            ex.printStackTrace();            
        }
        return response; 
    }

    @Override
    public ServiceResponse<Boolean> delete(String id) {
        ServiceResponse<Boolean> response = new ServiceResponse<Boolean>();
        boolean success = false;
        try {            
            List<User> records = MockDS.getUsers();   
            if (records != null && records.size() > 0) {
                
                for (int i = 0; i < records.size(); i++) {
                    User record = records.get(i);
                    
                    if (StringUtils.equalsIgnoreCase(record.getId(), id)) {
                        records.remove(i);
                        success = true;
                        break;
                    }
                }
            }            
            response.setResponse(success);
            response.setSuccessful(true);            
        } 
        catch (Exception ex) {
            response.setResponse(null);
            response.setSuccessful(false);
            response.setMessage(ex.getMessage());
            response.setException(ex);
            ex.printStackTrace();            
        }
        return response; 
    }

    private boolean emailExists(String email) {
        boolean exists = false;
        try {
            ServiceResponse<List<User>> sr1 = this.readAll(0, 0);
            if (sr1.isSuccessful() && sr1.getResponse() != null && sr1.getResponse().size() > 0) {
                for (User user : sr1.getResponse()) {
                    if (StringUtils.equals(user.getEmail().trim(), email.trim())) {
                        exists = true;
                    }
                }
            }            
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return exists;
    }
    
    @Override
    public ServiceResponse<Boolean> refreshLastLogin(String id) {
        ServiceResponse<Boolean> response = new ServiceResponse<Boolean>();
        boolean success = false;
        try {            
            List<User> records = MockDS.getUsers();   
            if (records != null && records.size() > 0) {
                
                for (int i = 0; i < records.size(); i++) {
                    User record = records.get(i);
                    
                    if (StringUtils.equalsIgnoreCase(record.getId(), id)) {
                        record.setLastLogin(new Date());
                        success = true;
                        break;
                    }
                }
            }            
            response.setResponse(success);
            response.setSuccessful(true);            
        } 
        catch (Exception ex) {
            response.setResponse(null);
            response.setSuccessful(false);
            response.setMessage(ex.getMessage());
            response.setException(ex);
            ex.printStackTrace();            
        }
        return response; 
    }

    //CX: users who have not yet posted a single listing
    @Override
    public ServiceResponse<List<User>> readDormatUsers() {
        ServiceResponse<List<User>> response = new ServiceResponse<List<User>>();
        List<User> users = new ArrayList<User>();
        
        IListingService listingService = new MListingService();        
        try {            
            List<User> records = MockDS.getUsers();   
            if (records != null && records.size() > 0) {
                
                for (int i = 0; i < records.size(); i++) {
                    User record = records.get(i);                    
                    ServiceResponse<List<Listing>> response1 = listingService.readUserListings(record.getId(), 0, 0);
                    
                    if (response1.isSuccessful()) {
                        if (response1.getResponse() == null || response1.getResponse().size() <= 0) {
                            users.add(record);
                        }
                    }
                }
            }            
            response.setResponse(users);
            response.setSuccessful(true);            
        } 
        catch (Exception ex) {
            response.setResponse(null);
            response.setSuccessful(false);
            response.setMessage(ex.getMessage());
            response.setException(ex);
            ex.printStackTrace();            
        }
        return response;
    }

    @Override
    public ServiceResponse<User> readByEmail(String email) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
}
